package com.sduept.nwld.wave.rest;

import com.alibaba.fastjson.JSONObject;
import com.sduept.core.dao.SuperDAO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 阻抗数据REST服务
 * @author Ningfw
 * @date 2017-06-21
 *
 */
@RestController
@RequestMapping("/impedance/")
public class ImpedanceServices {

	@Autowired
	private SuperDAO superDao;
	

	@GetMapping("/getImpedance/{fileId}/{lineId}")
	public String getImpedance(@PathVariable("fileId") String fileId,@PathVariable("lineId") String lineId){
		
//		JSONObject jso = new JSONObject();
		
		StringBuffer sqlSb = new StringBuffer();//查询全部阻抗sql字段
		StringBuffer xAxisSb = new StringBuffer();//查询全部阻抗sql列简化后的名称，作为x轴
		//故障前*ms值、故障前*ms相角
		StringBuffer preFaultStr = new StringBuffer();//故障前*ms值/相角
		StringBuffer xPreValue = new StringBuffer();//故障前*ms值/相角的x轴
		for(int i = 60; i >= 20; i = i-5){
			preFaultStr.append(","+("pre_fault_value_"+i)).append(","+("pre_fault_phase_"+i));
			xPreValue.append(",-"+i+"ms");
		}
		//故障后*ms值、故障后*ms相角
		StringBuffer postFaultStr = new StringBuffer();//故障后*ms值/相角
		StringBuffer xPostValue = new StringBuffer();//故障后*ms值/相角的x轴
		for(int i = 0; i <= 180; i = i+5){
			postFaultStr.append(","+("post_fault_value_"+i)).append(","+("post_fault_phase_"+i));
			xPostValue.append(","+i+"ms");
		}
		//重合闸后*ms值、重合闸后*ms相角
		StringBuffer reclosingValueStr = new StringBuffer();//重合闸后*ms值
		StringBuffer xRecloseValue = new StringBuffer();//故障后*ms值/相角的x轴
		for(int i = 0; i <= 180; i = i+5){
			reclosingValueStr.append(","+("reclosing_value_"+i)).append(","+("reclosing_phase_"+i));
			xRecloseValue.append(",+"+i+"ms");
		}
		sqlSb.append("phase_type").append(preFaultStr).append(postFaultStr).append(reclosingValueStr);
		xAxisSb.append(xPreValue.substring(1)).append(xPostValue).append(xRecloseValue);
		String[] xArr = xAxisSb.toString().split(",");//x轴
		
		String sqlImp = "SELECT "+sqlSb+" FROM t_lbtz_line_measure_impedance mi WHERE mi.fault_file_id = '"+fileId+"' "
			+ "AND mi.line_id = '"+lineId+"'";
		List<?> listImp = superDao.nativeQuery(sqlImp);

		StringBuffer stb = new StringBuffer();
		for(Object obj : listImp){
			List<String> valueList = new ArrayList<String>();//波形y轴（数据库中的*ms值）
			List<String> phaseList = new ArrayList<String>();//极坐标系y轴（数据库中的*ms相角值）
			Object[] objArr = (Object[])obj;
			Object[] objType = Arrays.copyOf(objArr, 1);//相别
			Object[] objs = Arrays.copyOfRange(objArr, 1, objArr.length);//数据
			for(int i=0; i < objs.length; i++){
				if(i % 2 == 0){//偶数为波形y值
					valueList.add(keepBit(objs[i].toString()));
				}else{//奇数为极坐标系y值
					phaseList.add(keepBit(objs[i].toString()));
				}
			}
			
			JSONObject keyValueJso = new JSONObject();//存放每一条数据的x轴和*ms相角的键值对
			for(int i=0; i < phaseList.size(); i++){
				keyValueJso.put(xArr[i], phaseList.get(i));
			}
			
			JSONObject impedanceObj = new JSONObject();//存放每一条数据的*ms和*ms相角的键值对
			impedanceObj.put("value", valueList);
			impedanceObj.put("phase", keyValueJso);
			
			String impedance;//键
			impedance = objType[0].toString();
//			jso.put(impedance, impedanceObj);//6条波，每一条波中都有*ms值和 x轴与*ms相角的键值对
			stb.append(",\"").append(impedance).append("\":").append(impedanceObj);
		}
		
//		jso.put("xAxis", xArr);//x轴
//		return jso.toJSONString();
		String xAxisStr = StringUtils.join(xArr,"\",\"");
		xAxisStr = "\"" + xAxisStr + "\"";
		String stbStr = "";
		if(StringUtils.isNotEmpty(stb.toString())){
			stbStr = stb.toString().substring(1);
		}
		String jsonStr = "{" + stbStr + ",\"xAxis\":[" + xAxisStr + "]}";
		return jsonStr;
	}
	
	/**
	 * 保留三位小数
	 * @param str
	 * @return
	 */
	public String keepBit(String str){
		if(null != str && !"".equals(str)){
			BigDecimal bd = new BigDecimal(str);
			String res = bd.setScale(3, BigDecimal.ROUND_HALF_UP).toString();
			return res;
		}else{
			return null;
		}
	}
	
}
